package me.hl.nio;


import org.junit.Test;

import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

//内存映射文件原理
public class MmapDemo {

    @Test
    public void test() throws Exception {
        try {
            int sum = 0;
            int n;
            long t1 = System.currentTimeMillis();
            FileInputStream fis = new FileInputStream("/Users/pulangke/dump.a2s.index");
            try {
                while ((n = fis.read()) >= 0) {
                    // 数据处理
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                fis.close();
            }
            long t = System.currentTimeMillis() - t1;
            System.out.println("传统IOread文件,不使用缓冲区,用时:" + t);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        try {
            int sum = 0;
            int n;
            long t1 = System.currentTimeMillis();
            FileInputStream fis = new FileInputStream("/Users/pulangke/dump.a2s.index");
            BufferedInputStream bis = new BufferedInputStream(fis);
            try {
                while ((n = bis.read()) >= 0) {

                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                bis.close();
            }
            long t = System.currentTimeMillis() - t1;
            System.out.println("传统IOread文件,使用缓冲区,用时:" + t);
        } catch (IOException e) {
            e.printStackTrace();
        }

        MappedByteBuffer buffer = null;
        try {
            int sum = 0;
            int n;
            long t1 = System.currentTimeMillis();

            File file = new File("/Users/pulangke/dump.a2s.index");
            FileInputStream fileInputStream = new FileInputStream(file);
            buffer = fileInputStream.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());

            for (int i = 0; i < 1024 * 1024 * 191; i++) {
                // 数据处理
            }
            long t = System.currentTimeMillis() - t1;
            System.out.println("内存映射文件读取文件,用时:" + t);
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }


    }

}
